/*----------------------------------------------
| noka mult input v1.0 www.97521.com           |
| rebin 2014-01-20                             |
|---------------------------------------------*/
var multinputtext = Class.create({
    version: '1.0',
    initialize : function(cfg) {
    	this.id=cfg.id; //id
    	this.cfg = cfg;
    	this.rurl=cfg.rurl;
    	this.icosrc=cfg.rurl+'/nokatag/formcheck/images/exclamation.gif';
    	this.input = $(cfg.id+'_input');
    	this.allownull=cfg.allownull;//是否允许为空
    	this.ico=$(cfg.id+'_img');
    	this.div=$(cfg.id+'_div');
    	this.maxDiv = ($(cfg.id+'_maxDiv')==undefined?undefined:$(cfg.id+'_maxDiv'));
    	this.chtype=cfg.chtype;//验证内型chtype js|server|regex
    	this.verification=cfg.verification;//验证内容
    	this.veriSuccess = cfg.allownull;
    	this.ajaxchtype = false;// 是否正在执行ajva验证
    	this.pva = cfg.pva;//页面参数 ['aaa','ccc']
    	this.readonly=(undefined==cfg.readonly?false:cfg.readonly);
    	this.disabled = (undefined==cfg.disabled?false:cfg.disabled);
    	this.maxclass = cfg.maxclass;
    	this.showpass = (cfg.showpass == undefined?false:cfg.showpass);
    	this.isshow = false;//是否显示
    	this.onShowMax = cfg.onShowMax;
    	this.inputPassInputStr = ($(cfg.id+'_intDiv')==undefined?undefined:$(cfg.id+'_intDiv').innerHTML);
    	this.bodyHeight = (cfg.bodyHeight == undefined?200:cfg.bodyHeight);
    	this.json = [];
    	this.findsql = cfg.findsql;
    	this.ndataLang = cfg.ndataLang;
    	this.onchange = cfg.onchange;
    	this.selectIndex = -1;//当前选种行
    	this.ondelete = cfg.ondelete;
    	this.findurl = (undefined==cfg.findurl?this.rurl+'/nokatag/nselect'+this.id+'.ajaxinput':cfg.findurl);
    },
    initinput : function(){
    	this.initPassInput();
    	this.initIco();
    	this.initMsg();
    	this.initMaxMsg();
    	this.InputVerEvent();
    	this.msgShowHide();
    	this.initObjCht();
    	this.onChangeColor();
    	this.multinitvalue();
    },
    //---------初始化input----------------
    initPassInput : function(){
    	var self = this;
    	var inputstr = self.inputPassInputStr;
    	var inputValue = ($(self.id)==undefined?'':$(self.id).value);
    	if(inputstr!=undefined){
	    	if(self.isshow){
	    		$(self.id+'_intDiv').innerHTML=inputstr.replace(/\{type\}/g,'text');
	    	}else{
	    		$(self.id+'_intDiv').innerHTML=inputstr.replace(/\{type\}/g,'password');
	    	}
	    	self.input = $(self.id);
	    	self.input.value=inputValue;
	    	self.InputVerEvent();
	    	self.initMaxMsg();
	    	self.PassWordButton();
	    	var chbutton = $(self.id+'_chdiv');
	    	if(chbutton!=undefined && self.showpass){
		    	if(self.isshow){
		    		chbutton.innerHTML='ON';
		    		chbutton.setStyle({backgroundColor:'#76c61d'});
		    	}else{
		    		chbutton.innerHTML='OFF';
		    		chbutton.setStyle({backgroundColor:'#14bbf9'});
		    	}
	    	}
    	}
    },
    //---------初始化ico------------------
    initIco : function(){
	   this.ico.src = this.icosrc;
	   this.ico.setStyle({verticalAlign:'middle'});
	   this.ico.hide();
	   this.input.setStyle({verticalAlign:'middle'});
    },
    //---------初始化msgdiv--------------
    initMsg : function(){
    	this.div.setStyle({display:'block',background:'#FFFFFF',border:'solid 1px #FF0000',zIndex:'9999',padding:'5px 5px 5px'});
    	this.div.absolutize();
    	if(this.maxDiv!=undefined){
    		this.maxDiv.innerHTML='&nbsp;';
    	}
    	this.div.hide();
    },
    //--------初始化放大层--------------
    initMaxMsg : function(){
    	var inobj = this.input;
    	if(this.maxDiv!=undefined){
	    	this.maxDiv.absolutize();
	    	this.maxDiv.setStyle({display:'block',background:'#FFFFFF',border:'solid 1px #FF0000',zIndex:'9999',padding:'5px 5px 5px'});
	    	this.maxDiv.style.top=inobj.positionedOffset().top-this.maxDiv.offsetHeight-5;//
	    	this.maxDiv.style.left=inobj.positionedOffset().left-2;//+inobj.offsetWidth;
	    	this.maxDiv.hide();
    	}
    },
    //---------初始化放大效果---------------
    showMax : function(v){
        if(this.maxDiv!=undefined){
	    	if(v.trim().length>0){
	    		if(this.onShowMax!=undefined){
	    			this.maxDiv.show();
	    	    	this.maxDiv.innerHTML=this.onShowMax(v);
	    		}else{
	    			this.maxDiv.show();
	    	    	this.maxDiv.innerHTML=v;
	    		}
	    	}else{
	    		this.maxDiv.hide();
	    	}
        }
    },
    //---------初始化密码显示按钮----------------
    PassWordButton:function(){
    	var self = this;
    	var idx = 0;
    	var html=[];
    	var lenWidth = 4;
    	if(self.showpass){
    		lenWidth=35;
    		html[idx++]='<div id="'+self.id+'_chdiv" style="background-color:#14bbf9;width:30px;line-height:20px;height: 20px;text-align:center;margin:0 auto;cursor:pointer;float:right;border-left: 1px solid #AFAFAF;font-size:10px;">OFF</div>';
    	}else{
    		html[idx++]='<div id="'+self.id+'_chdiv" style="width:1px;line-height:20px;height: 20px;text-align:center;margin:0 auto;float:right;border:0;"></div>';
    	}
    	if($(self.id+'_chbut')!=undefined){
	    	$(self.id+'_chbut').innerHTML=html.join('');
	    	var inputWidth = self.input.getWidth()-lenWidth;
	    	self.input.setStyle({width:inputWidth+'px'});
	    	self.input.width=inputWidth;
	    	$(self.id+'_chdiv').observe('click',function(){//失失焦点时验证其值
	    		self.isshow = !self.isshow;
	    		self.initPassInput();
	     	 });
    	}
    },
    //--------初始化验证-----------------
    initObjCht : function(){
    	var self = this;
    	$(self.id).veri = function(){
			self.chVeris();//验证
			if(!self.veriSuccess)
				self.ico.show();
	    	return self.veriSuccess;
    	};
    	$(self.id).setValue = function(value,ch){//1,2
    		$(self.id).value = value;//设置值
    		if(typeof ch == 'undefined'){
    			self.chVeris();//验证
    		}else{
    			self.veriSuccess=ch;
    			if(!ch){
    				$(self.id+'_img').show();
    			}else if(ch){
    				$(self.id+'_img').hide();
    			}
    		}
    		self.multinitvalue();
    	};
    	//------------------------------------
    	$(self.id).isServer = function(){//是否为服务器验证
    		return 'server'==self.chtype;
    	};
    	//-----------------------------------
    	$(self.id).isVeriEnd = function(){//是否验证结束
    		return !self.ajaxchtype;//为false表示验证结束
    	};
    	//----------------------------------
    	$(self.id).sVerEnd = function(){//服务器验证结果
    		return  self.veriSuccess;
    	};
    	$(self.id).setDisabled = function(a){
    		$(self.id+'_input').writeAttribute({disabled:a});
    		self.disabled=a;
    	};
    	$(self.id).setReadonly = function(a){
    		$(self.id+'_input').writeAttribute({readonly:a});
    		self.readonly=a;
    	};
    },
    //---------增加验证事件---------------
    InputVerEvent : function(){
    	 var self = this;
    	 self.input.observe('blur',function(){//失失焦点时验证其值
    		 if($(self.id+'_input').value.trim().length>0){
		     		self.setMultValue();
  			 }
    		self.chVeris();
    	 });
    	 if(self.maxclass != undefined){
    		//-----------增加放大效果-----------------------------------
			 self.input.observe('keyup',function(){//失失焦点时验证其值
				 var ispassword = $(self.id+'_chbut');
				 if(ispassword== undefined){//不是密码输入框
					 self.showMax(this.value);
				 }else if(self.isshow){//是密码框，必须是在显示密码状态下放大效果才起作用
					 self.showMax(this.value);
				 }
     	 	});
			 //-----------隐藏-----------------------------------------
		 	document.observe('mouseout',function(event){
		   	 	if(self.div.visible){//图标可见
		   	 		if(self.maxDiv!=undefined){
			 			self.maxDiv.hide();
		   	 		}
			 	}
	   	 	});
    	 }
    	//--------------多项输入----------------------------------------
     	self.input.observe('keyup',function(event){//失失焦点时验证其值
     		if(event.keyCode == 13) {//回车
     			if(self.json.length>0){
     				if(self.selectIndex>-1){//选择输入
	     				var v=$(self.id+'_'+self.selectIndex+'_value').value;
	        			var t=$(self.id+'_'+self.selectIndex+'_text').value;
	        			self.tempJSON={idx:self.selectIndex,value:v,text:t};
	        			try{$(self.id+'_img').hide();}catch(e){}//隐藏错误消息
	        			self.setMultValue(t);
     				}
     			}else if($(self.id+'_input').value.trim().length>0){
     				self.tempJSON={idx:-1,value:'',text:$(self.id+'_input').value};
		     		self.setMultValue();
     			}
     		 }else if(event.keyCode == 40){//40向下
	     		if($(self.id+'_selectbody').visible()){
	     			self.selectBodykeyEvent(false);
	     		}
	     	 }else if(event.keyCode == 38){//38向上
	     		if($(self.id+'_selectbody').visible()){
	     			self.selectBodykeyEvent(true);
				}
	     	}else if(event.keyCode==27){//27
	     		$(self.id+'_selectbody').hide();
	     	}else{
	     		self.ajaxSelect();
	     	}
     	});
     	self.selectBodyShowHide();
     	document.observe('widget:noka_reinit',function(event){//失失焦点时验证其值
        	if(self.id.indexOf('_nkADinsert_')==-1){
     	    	var npfffs=event.memo.widgetNumber.clone();
     	    	for(var i=0;i<npfffs.length;i++){
     	    		var cfgid = Object.allclone(self.cfg);
     	    		var initem = npfffs[i];
	    			cfgid.id = initem.id;
	    			if(undefined!=initem.value){
	    				cfgid.value=initem.value;
	    			}
     	    		if(cfgid.id.indexOf('_'+self.id+'_')!=-1){
     	    			(new multinputtext(cfgid)).initinput();
     	    			$(cfgid.id).setValue('');
     	    			try{
	    					var idx = cfgid.id.substring(cfgid.id.lastIndexOf('_')+1,cfgid.id.length);
	    					$(cfgid.id).name=$(cfgid.id).name.replace(/\[0\]/g,'['+idx+']');
	    					if(undefined!=initem.value && $(cfgid.id).name==initem.name){
	    						$(cfgid.id).setValue(initem.value);
	    					}
	    				}catch(e){}
     	    		}
     	    	}
        	}
        });
    },
    //====================================================================================================
    ajaxSelect : function(){
    	var self = this;
    	var idx = 0;//
       	var parsv=[];
       	var val = $(self.id+'_input').value;
       	if(val.length<self.qulenght){
       		return;
       	}
       	parsv[idx++]=(''==self.findsql?'':'&sql='+self.findsql);
       	parsv[idx++]=('&pare='+val);
    	new Ajax.Request(self.findurl, {
    	    method:'post',
    	    parameters: parsv.join(''),
    	    onSuccess: function(response) {
    	    	self.json = response.responseText.evalJSON();
    	    	self.jsonList();
    	       }
    	   });
    },
    //------------------------list body--------------------------------
    jsonList : function(){
    	var self = this;
    	var obj = $(self.id+'_input');
    	var pos = obj.positionedOffset();
    	var sebody = $(self.id+'_selectbody');
    	var dtop = pos.top+obj.offsetHeight+2;
    	var dleft = pos.left-1;
    	var idx = 0;
    	var html=[];
    	var Lheight=0;
    	var Lwidth = 0;
    	var AWidth = 2;
    	var json = self.json;
    	sebody.setStyle({width:'',height:''});
    	html[idx++] = '<table id="'+self.id+'_bodytable" style="border:0;" cellpadding="0" cellspacing="0"> ';
    	for(var i=0;i<json.length;i++){
    		html[idx++] = '<tr><td id="'+self.id+'_'+i+'" style="font-size:12px;padding:0;height:25px;color:#000000;" title="'+json[i].text+'" alt="'+json[i].text+'">';
    		html[idx++] = json[i].text;
    		html[idx++] = '<input type="hidden" value="'+json[i].value+'" id="'+self.id+'_'+i+'_value">';
    		html[idx++] = '<input type="hidden" value="'+json[i].text+'"  id="'+self.id+'_'+i+'_text">';
    		html[idx++] = '<input type="hidden" value="'+i+'"  id="'+self.id+'_'+i+'_idx">';
    		html[idx++] = '</td></tr>';
    		Lheight+=28;
    	}
    	if(json.length<1){
    		html[idx++] = '<tr><td style="height:25px;font-size:12px;padding:0;">'+self.ndataLang+'</td></tr>';
    		Lheight+=28;
    	}
    	if(Lheight>self.bodyHeight){
    		Lheight = self.bodyHeight;
    		AWidth+=18;
    	}
    	
    	html[idx++] = '</table>';
    	sebody.innerHTML=html.join('');
    	sebody.setStyle({left:dleft+'px',top:dtop+'px',height:Lheight+'px'});
    	sebody.show();
    	if(undefined!= self.showhide){
    		self.showhide(false);//
    	}
    	Lwidth = $(self.id+'_bodytable').getWidth();
    	IWidth = $(self.id).getWidth();
    	if(Lwidth<IWidth){
    		sebody.setStyle({width:(IWidth+AWidth)+'px'});
    		sebody.style.width=(IWidth+AWidth)+'px';
    	}else{
    		sebody.setStyle({width:(Lwidth+AWidth)+'px'});
    		sebody.style.width=(Lwidth+AWidth)+'px';
    	}
    	self.selectBodyEvent();
    	self.selectIndex=-1;
    	if(json.length>0){
    		self.selectIndex=0;
    		$(self.id+'_0').setStyle({color:'#ffffff',backgroundColor:'#000080'});
    	}
    },
    //-----------------------------------------------------------------
    selectBodyEvent : function(){
    	var self = this;
        var json = self.json;
    	for(var i=0;i<json.length;i++){
    		$(self.id+'_'+i).observe('click',function(a){
    			var v=$(this.id+'_value').value;
    			var t=$(this.id+'_text').value;
    			var idx=$(this.id+'_idx').value;
    			self.tempJSON={idx:idx,value:v,text:t};
    			try{$(self.id+'_img').hide();}catch(e){}
    			self.setMultValue(t);
            });
    		$(self.id+'_'+i).observe('mousemove',function(a){
    			this.setStyle({color:'#ffffff',backgroundColor:'#000080'});
            });
    		$(self.id+'_'+i).observe('mouseout',function(a){
    			this.setStyle({color:'#000000',backgroundColor:'#ffffff'});
            });
    	}
    },
    selectBodykeyEvent : function(a){
    	var self = this;
    	var json = self.json;
    	var mx = json.length-1;
    	var sm = (self.bodyHeight/27)-1;
    	try{
	    	try{
	    		$(self.id+'_'+self.selectIndex).setStyle({color:'#000000',backgroundColor:'#ffffff'});//设置上一个选择项为未选择状态
	    	}catch(e){}
	    	if(a){//向上
	    		self.selectIndex--;
	    		if(self.selectIndex<0){
	    			self.selectIndex=0;
	    		}
	    		$(self.id+'_'+self.selectIndex).setStyle({color:'#ffffff',backgroundColor:'#000080'});
	    		$(self.id+'_selectbody').scrollTop-= (((sm+2)-self.selectIndex)*27);
	    	}else{//向下
	    		self.selectIndex++;
	    		if(self.selectIndex>mx){
	    			self.selectIndex=mx;
	    		}
	    		$(self.id+'_'+self.selectIndex).setStyle({color:'#ffffff',backgroundColor:'#000080'});
	    		$(self.id+'_selectbody').scrollTop+= ((self.selectIndex-sm)*27);
	    	}
    	}catch(es){}
    },
    selectBodyShowHide : function(){
    	var self = this;
    	var miFlg = true;
    	var obj = $(self.id+'_input');
    	var tre = $(self.id+'_selectbody');
    	var sdy = $(self.id+'_sdDiv');
    	obj.observe('mousemove',function(){
    		miFlg = true;
    	});
        obj.observe('mouseout',function(event){
        	miFlg = false;
        	var element = event.element();
        	setTimeout(function(){
                if (element.descendantOf(sdy) && !miFlg){
                	tre.hide();
                	if(undefined!= self.showhide){
                		self.showhide(true);//
                	}
                }
            }, 500);
        });
        tre.observe('mousemove',function(){
    		miFlg = true;
    	});
        tre.observe('click',function(){
    		miFlg = true;
    	});
        tre.observe('mouseout',function(event){
        	miFlg = false;
        	var element = event.element();
        	setTimeout(function(){
                if (element.descendantOf(tre) && !miFlg){
                	tre.hide();
                	if(undefined!= self.showhide){
                		self.showhide(true);//
                	}
                }
            }, 200);
        });
    },
    //----------------------------------------------------------------------------
    setMultValue : function(v){
    	var self = this;
    	if(undefined==v){
    		v = $(self.id+'_input').value;
    	}
    	var isOnchange = true;//是否继续执行
    	//-----------------------------------------------------------------------
    	try{
	    	if(undefined!=self.onchange){
	    		var ob = {obj:$(self.id),selectvalue:{value:self.tempJSON.value,text:self.tempJSON.text}};
	    		isOnchange = self.onchange(ob);
	    	}
    	}catch(e){}
    	if(false == isOnchange){
    		return;
    	}
    	$(self.id+'_multinput').innerHTML+='<div class="'+self.id+'_mulidivs nk_ajaxinput_vluediv nk_input_lineheight">'+v+'</div>';
		$(self.id+'_input').value='';
		$$('div.'+self.id+'_mulidivs').each(function(alink,index) {
			 $(alink).observe('click',function(){//失失焦点时验证其值
				 if(self.deleteUser(alink)){
					 $(alink).remove();
					 self.multvalue();
				 }
			 	try{
			 		$(self.id).focus();
			 	}catch(e){}//显示时，设置焦点
			 });
	    });
		self.multvalue();
    },
    //============================================================================
    multinitvalue : function(){
    	var self = this;
    	var vals = $(self.id).value.split(',');
    	try{
    		$(self.id+'_multinput').innerHTML='';
    		for(var i=0;i<vals.length;i++){
    			if(vals[i].trim().length>0)
    				$(self.id+'_multinput').insert('<div class="'+self.id+'_mulidivs nk_ajaxinput_vluediv nk_input_lineheight">'+vals[i]+'</div>');
    		}
    		$(self.id+'_input').value='';
    		$$('div.'+self.id+'_mulidivs').each(function(alink,index) {
	     			 $(alink).observe('click',function(){//失失焦点时验证其值
	     				if(self.deleteUser(alink)){
	     					$(alink).remove();
	     					self.multvalue();
	     				}
	     			 	try{
	     			 		$(self.id).focus();
	     			 	}catch(e){}//显示时，设置焦点
	     			 });
	     	 });
    		self.multvalue();
    	}catch(e){}
    },
    //-----------------------------------------------------------------
    deleteUser : function(alink){
    	var self = this;
    	var isremove = true;
    	if(self.readonly || self.disabled){
    		return false;
    	}
		try{
			if(undefined !=self.ondelete){
				isremove = self.ondelete($(alink));
			}
			if(undefined == isremove){
				isremove = true;
			}
		}catch(e){}
		return isremove;
    },
    //-----------------多项输入获取值---------------------------------------
    multvalue : function(){
    	var self = this;
    	var vals = '';
    	$$('div.'+self.id+'_mulidivs').each(function(alink,index) {
    		vals+= $(alink).innerHTML+',';
    	});
    	if(vals.indexOf(',')!=-1){
    		vals = vals.substring(0, vals.length-1);	
    	}
    	$(self.id).value = vals;
    	if(vals.length>0){
    		$(self.id+'_multinput').show();
    	}else{
    		$(self.id+'_multinput').hide();
    	}
    },
    //-----------------------------------------------------------------
    chVeris : function(){
    	var self = this;
    	var va = $(self.id).value;
    	if((va.trim().length<1) && !self.allownull){//不允许为空
			 self.ico.show();
			 self.veriSuccess=false;
			 self.ajaxchtype = false;//为false表示验证结束
		 }else if(va.trim().length>0){//有输入内容
			 var vas = va.split(',');
			 if(''!=self.verification){
				for(var i=0;i<vas.length;i++){
					 var chend = false;//验证结果
					 if('js'==self.chtype){
						 chend=self.chInputJs(vas[i]);
					 }else if('regex'==self.chtype){
						 chend=self.chInputRegex(vas[i]);
					 }else if('server'==self.chtype){
						 self.ajaxchtype = true;// 是否正在执行ajva验证
						 self.chInputServer(vas[i]);
						 chend = true;
					 }
					 if(!chend){
						 self.ico.show();
						 self.veriSuccess=false;
						 return;
					 }else{
						 self.ico.hide();
						 self.veriSuccess=true;
					 }
				}
		 }else{//没有输入内容，可以为空
			 self.ico.hide();
			 self.veriSuccess=true;
		 }
	   }
    },
    //--------regex------------------------
    chInputRegex : function(value){
    	var regu = "^" + this.verification + "$";
    	var re = new RegExp(regu);
    	return re.test(value);
    },
    //---------自定义js验证-----------------
    chInputJs : function(value){
    	return this.verification(value);
    },
    //---------服务端验证-------------------
    chInputServer : function(value){
    	var self = this;
    	var idx = 0;//
    	var parsv=[];
    	parsv[idx++]='fun='+self.verification;
    	parsv[idx++]='&thisvalue='+value;
    	if(self.pva!=undefined){
    		try{
	    		for(var c=0;c<self.pva.length;c++){
	    			parsv[idx++]='&'+self.pva[c]+'='+$(self.pva[c]).value;
	    		}
    		}catch(E){}
    	}
    	new Ajax.Request(self.rurl+'/nokatag/ajax/inputtextcheck'+self.id+'.itck', {
    		method:'post',
            parameters: parsv.join(''),
            onSuccess: function(response) {
            	var v = response.responseText;
            	if('1'==v){//成功
            		self.ico.hide();
            		self.veriSuccess = true;
            	}else{//失败
            		self.ico.show();
            		self.veriSuccess=false;
            	}
            	self.ajaxchtype = false;//验证完成
            },
            onFailure : function(transport) {
            	self.ajaxchtype = false;//验证完成
            }
    	});
    },
    //-------------空验证------------------
    chInputNull : function(value){
    	if (''==value)
    		return true;
    	var regu = "^[ ]+$";
    	var re = new RegExp(regu);
    	return re.test(value);
    },
    //--------消息提示显示、隐藏------------
    msgShowHide : function(){
    	var self = this;
   	 	self.ico.observe('mousemove',function(){//失失焦点时验证其值
   	 		if(self.ico.visible){//图标可见
   	 			self.div.absolutize();
   	 			self.div.style.top=self.ico.positionedOffset().top+self.ico.offsetHeight;//
   	 			self.div.style.left=self.ico.positionedOffset().left+self.ico.offsetWidth;
   	 			self.div.setStyle({top:(self.ico.positionedOffset().top+self.ico.offsetHeight)+'px',left:(self.ico.positionedOffset().left+self.ico.offsetWidth)+'px'});
   	 			self.div.show();
   	 		}
   	 	});
   	 	self.ico.observe('mouseout',function(event){
	   	 	if(self.div.visible){//图标可见
		 		self.div.hide();
		 	}
   	 	});
    },
    onChangeColor : function(){
    	var self = this;
    	var obj = $(self.id+'_sdDiv');
    	obj.observe('mousemove',function(){
     		self.setSelectStyle(obj);
     	});
    	
         obj.observe('mouseout',function(event){
         	var element = event.element();
         	setTimeout(function(){
                 	self.setNoSelectStyle(obj);
             }, 500);
         });
    },
    //----------选种状态-----------------------
    setSelectStyle : function(obj){
    	obj.setStyle({borderColor:'#5794bf'});
    },
    //-----------未选种状态-------------------
    setNoSelectStyle : function(obj){
    	obj.setStyle({borderColor:'#AFAFAF'});
    }
});